package com.eii.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.eii.common.constant.BusinessTypeConstants;
import com.eii.common.constant.UserConstants;
import com.eii.common.utils.StringUtils;
import com.eii.common.web.controller.BaseController;
import com.eii.common.web.domain.Result;
import com.eii.common.web.page.PageResult;
import com.eii.excel.util.ExcelUtils;
import com.eii.log.annotation.AuditLog;
import com.eii.oauth2.common.annotation.InnerAuth;
import com.eii.oauth2.common.annotation.RequiresPermissions;
import com.eii.oauth2.common.util.SecurityUtils;
import com.eii.system.api.domain.SysRole;
import com.eii.system.api.domain.SysUser;
import com.eii.system.api.model.LoginUser;
import com.eii.system.controller.vo.SysUserExcel;
import com.eii.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    private final static String CONTROLLER_TITLE = "用户管理";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public PageResult list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getPageResult(list);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException {
        List<SysUser> users = userService.selectUserList(user);
        List<SysUserExcel> sysUserExcels = users.stream()
                .map(u -> {
                    SysUserExcel sysUserExcel = BeanUtil.copyProperties(u, SysUserExcel.class);
                    sysUserExcel.setDeptName(u.getDept().getDeptName());
                    sysUserExcel.setLeader(u.getDept().getLeader());
                    return sysUserExcel;
                })
                .collect(Collectors.toList());
        String datestr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String filename = "用户数据" + datestr + ".xlsx";
        ExcelUtils.exportExcelStream(response, filename, SysUserExcel.class, sysUserExcels);
    }

    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public Result importData(MultipartFile file, boolean updateSupport) throws Exception {
        List<SysUserExcel> userImportList = ExcelUtils.read(file, SysUserExcel.class);
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userImportList, updateSupport, operName);
        return Result.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<SysUserExcel> sysUserExcels = new ArrayList<>(0);
        String filename = "用户数据模板.xlsx";
        ExcelUtils.exportExcelStream(response, filename, SysUserExcel.class, sysUserExcels);
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public Result<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (sysUser == null) {
            return Result.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return Result.success(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public Result register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return Result.fail("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            return Result.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return Result.success(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", userService.selectUserById(userId));
        resultMap.put("roles", roles);
        resultMap.put("permissions", permissions);
        return Result.success(resultMap);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        Result ajax = Result.success();
        List<SysRole> roles = roleService.selectRoleAll();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        resultMap.put("posts", postService.selectPostAll());
        if (userId != null) {
            SysUser sysUser = userService.selectUserById(userId);
            resultMap.put("user", sysUser);
            resultMap.put("postIds", postService.selectPostListByUserId(userId));
            resultMap.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return Result.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Result.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Result.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toResult(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping
    public Result edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return Result.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return Result.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toResult(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.DELETE)
    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable Long[] userIds) {
        if (ArrayUtil.contains(userIds, SecurityUtils.getUserId())) {
            return Result.fail("当前用户不能删除");
        }
        return toResult(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping("/resetPwd")
    public Result resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toResult(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.UPDATE)
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toResult(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public Result authRole(@PathVariable("userId") Long userId) {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", user);
        resultMap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return Result.success(resultMap);
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @AuditLog(title = CONTROLLER_TITLE, operation = BusinessTypeConstants.GRANT)
    @PutMapping("/authRole")
    public Result insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return Result.success();
    }
}
